<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* ---- */
const user = reactive({
  id: 0,
  show: false,
  btnTxt: '邀请加入【万域商友会】',
  linkurl: '',
  telphone: proxy.$telPhone,
  wechat_img: proxy.$imgEwm,
  // ----
  title: '',
  // ----
  share_name: '万域商友会总经理',
  share_leader: '陈鹏',
  share_title: proxy.$shareTitle,
  share_desc: '',
  share_icon: proxy.$shareIcon,
  // ----
  musicPlay: 'paused',
  musicId: 0,
  musicUrl: ''
})
// ----
let topFixH = 0
const forScroll = ref(false)
// ----
let musics = []
const tbtns = ref([])
// ----
const padStyle = ref({})
// ----
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// --设置微信分享--
const setWebShare = (info) => {
  const forSn = proxy.$Store.get('SN')
  const currentUrl = window.location.href.split('#')[0]
  const shareLink = (Number(currentUrl.indexOf('sn=')) === Number(-1)) ? ((Number(currentUrl.indexOf('?')) === Number(-1)) ? currentUrl + '?sn=' + forSn : currentUrl + '&sn=' + forSn) : currentUrl
  proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
    if (!obj) return
    // ----
    obj.hideMenuItem()
    obj.showMenuList(['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:favorite', 'menuItem:share:QZone'])
    // ----
    obj.share({
      title: info.title,
      desc: info.desc,
      link: shareLink,
      imgUrl: info.imgUrl
    })
  })
}
// ----
const audioPlay = () => {
  proxy.$refs.bgMusic.play()
  document.removeEventListener('touchstart', audioPlay)
}
// ----
const getCurrencyInfo = async () => {
  // --获取背景音乐集--
  const musicItems = forSys.filter((item) => { return String(item.name) === 'market_bgMusic' })
  if (Number(musicItems.length) === 1) {
    await proxy.$Myfun.getJsonData(musicItems[0].value, (resJson) => {
      if (Number(resJson[0].list.length) > 0) musics = resJson[0].list
    })
  }
  // --获取合作商家信息--
  const forPlanData = { params: { 'ProgramSearch[id]': proxy.$route.query.id } }
  await proxy.$Axios.all([
    proxy.$Axios.get('program/index', forPlanData)
  ]).then(proxy.$Axios.spread((planData) => {
    const PData = planData.items[0] || {}
    // ----
    user.id = PData.dealer_id
    user.show = Number(PData.unset_title) === 1
    if (PData.btn_words) user.btnTxt = proxy.$Myfun.setText(PData.btn_words)
    if (PData.btn_link) user.linkurl = proxy.$Myfun.setText(PData.btn_link)
    // ----
    user.title = proxy.$Myfun.setText(PData.title)
    // ----
    if (PData.page_title) user.share_title = proxy.$Myfun.setText(PData.page_title)
    proxy.$Myfun.getJsonData(PData.description, (resJson) => {
      if (resJson[0].share_desc) user.share_desc = proxy.$Myfun.setText(resJson[0].share_desc)
    })
    proxy.$Myfun.getJsonData(PData.icon, (resJson) => {
      if (Number(resJson.length) > 0) user.share_icon = resJson[0].image
    })
    // ----
    user.musicId = PData.music_id
    // ----
    const newItems = []
    proxy.$Myfun.getJsonData(PData.img_json, (resJson) => {
      resJson.forEach((item) => {
        newItems.push({
          image: item.image,
          width: item.width,
          height: item.height
        })
      })
    })
    items.value = newItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  musics.some((current) => {
    if (String(current.id) === String(user.musicId)) user.musicUrl = current.link
  })
  // --获取用户信息--
  await proxy.$http.get('dealer/index', {
    params: { 'DealerSearch[id]': user.id }
  }).then((res) => {
    const UData = res.items[0] || {}
    // ----
    if (UData.name && Number(UData.name.length) > 0) user.share_name = proxy.$Myfun.setText(UData.name)
    if (UData.leader && Number(UData.leader.length) > 0) user.share_leader = proxy.$Myfun.setText(UData.leader)
    // ----
    user.telphone = UData.tag || UData.telphone
    proxy.$Myfun.getJsonData(UData.wechat_img, (resJson) => {
      if (Number(resJson.length) > 0) user.wechat_img = resJson[0].image
    })
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --获取分享者联系方式--
  if (proxy.$route.query.sn) {
    await proxy.$http.get('dealer/index', {
      params: { 'DealerSearch[sn]': proxy.$route.query.sn }
    }).then((res) => {
      const UData = res.items[0] || {}
      // ----
      if (UData.name && Number(UData.name.length) > 0) user.share_name = proxy.$Myfun.setText(UData.name)
      if (UData.leader && Number(UData.leader.length) > 0) user.share_leader = proxy.$Myfun.setText(UData.leader)
      // ----
      user.telphone = UData.tag || UData.telphone
      proxy.$Myfun.getJsonData(UData.wechat_img, (resJson) => {
        if (Number(resJson.length) > 0) user.wechat_img = resJson[0].image
      })
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  if (Number(user.share_desc.length) === 0) user.share_desc = '邀请人：' + user.share_leader + '@' + user.share_name
  // ----
  tbtns.value = [{
    show: true,
    icon: 'fal fa-comments',
    callback: () => {
      let options = {
        title: proxy.$Global.layer.titleTwo + user.telphone,
        content: proxy.$Global.layer.conEver,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnAsk,
          class: 'xw-color-24',
          callback: () => { window.location.href = 'tel:' + user.telphone }
        }]
      }
      if (user.wechat_img) {
        options = {
          title: proxy.$Global.layer.titleFour,
          content: '<div style="padding: 0 2.4rem;"><img src="' + user.wechat_img + '" style="width: 100%;"/></div>',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: proxy.$Global.layer.btnAsk,
            class: 'xw-color-24',
            callback: () => { window.location.href = 'tel:' + user.telphone }
          }]
        }
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
    }
  }, {
    show: true,
    icon: 'fal fa-phone-volume',
    callback: () => { window.location.href = 'tel:' + user.telphone }
  }]
  // ----
  proxy.$Myfun.getFotH().then((resFot) => { padStyle.value = { paddingBottom: resFot + 'px' } })
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
  // --设置微信分享功能--
  const forShare = {
    title: user.share_title,
    desc: user.share_desc,
    imgUrl: user.share_icon
  }
  setWebShare(forShare)
  // ----
  if (user.musicUrl && Number(user.musicUrl.length) > 0) document.addEventListener('touchstart', audioPlay)
  // ----
  setTimeout(() => {
    const childItems = []
    const nodeItems = document.querySelector('.invit-list').childNodes
    nodeItems.forEach((item, index) => {
      if (String(item.nodeName) !== '#text') childItems.push(item.offsetHeight)
    })
    topFixH = childItems[0] || 0
    // ----
    window.addEventListener('scroll', handleScroll)
  }, 200)
}
const handleScroll = () => {
  // --滚动到指定位置显示和隐藏层，并对应滚动文字--
  if (user.show) {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    if (Number(scrollTop) >= Number(topFixH)) {
      forScroll.value = true
    } else {
      forScroll.value = false
    }
  }
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      if (String(user.musicPlay) === 'running') {
        proxy.$refs.bgMusic.pause()
      } else {
        proxy.$refs.bgMusic.play()
      }
      break
    }
    case 2: {
      user.musicPlay = 'paused'
      break
    }
    case 3: {
      user.musicPlay = 'running'
      break
    }
    case 4: {
      if (Number(user.linkurl.length) > 0) {
        window.location.href = user.linkurl
        return false
      }
      // ----
      proxy.$Myfun.openPage(proxy, 'push', 'UcenTer')
      break
    }
    case 5: {
      item.callback && item.callback()
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getCurrencyInfo()
})
onBeforeUnmount(() => { document.removeEventListener('touchstart', audioPlay) })
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="invit-list" :style="padStyle">
      <div v-for="(item, index) in items"><img :src="item.image"/></div>
    </div>
    <transition name="fade"><div class="INIT-fix xw-bgCL-11 xw-flex xw-flex-align " v-show="user.show && forScroll">
      <div class="INIT-fix-title">邀请人：</div>
      <div class="INIT-fix-con xw-ellipsis xw-flex-W1"><em class="xw-color-18">{{user.share_leader}}</em><span class="xw-color-23">@{{user.share_name}}</span></div>
    </div></transition>
    <transition name="fade"><div class="INIT-music xw-act xw-radius-round INIT-rotate xw-flex xw-flex-center xw-flex-column" :style="{'animation-play-state': user.musicPlay}" @click="getAuditFun(1)" v-if="user.musicUrl && Number(user.musicUrl.length) > 0"><em class="fal fa-music-note xw-color-18"></em></div></transition>
    <div class="INIT-audio"><audio ref="bgMusic" :src="user.musicUrl" @pause="getAuditFun(2)" @play="getAuditFun(3)" preload loop></audio></div>
    <footer>
      <div class="tabs xw-foot-Tfg xw-flex xw-flex-align">
        <div class="TAB-mbtn xw-radius-3 xw-bgCL-11 xw-act xw-ellipsis xw-flex-W1" @click="getAuditFun(4)">{{user.btnTxt}}</div>
        <div class="TAB-btn xw-bgCL-21 xw-radius-3 xw-flex">
          <template v-for="(item, index) in tbtns">
            <div class="xw-act xw-Lfg xw-flex xw-flex-center" @click="getAuditFun(5, item)" v-if="item.show"><em :class="item.icon"></em></div>
          </template>
        </div>
      </div>
    </footer>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.invit-list img { width: 100%; }

/* ---- */
.INIT-fix { position: fixed; padding: 0 1rem; top: 0; left: 0; right: 0; height: 4.5rem; z-index: 999; }
.INIT-fix-title { font-size: 1.7rem; }
.INIT-fix-con { font-size: 1.7rem; }
.INIT-fix-con em { margin-right: 0.5rem; }

/* ---- */
.INIT-music { position: fixed; width: 4.6rem; height: 4.6rem; right: 0.5rem; top: 7rem; background: rgba(0, 0, 0, 0.5); z-index: 9999; }
.INIT-music em { font-size: 2.4rem; }
.INIT-rotate { animation: rotating 3s linear infinite; }
.INIT-audio { display: none; height: 0; }

/* ---- */
.tabs { padding: 0 1rem; }
.TAB-mbtn { height: 4rem; line-height: 4rem; font-size: 1.6rem; }
.TAB-btn { margin: 0 0 0 1rem; height: 4rem; }
.TAB-btn div { padding: 0 1.4rem; }
.TAB-btn div:before { top: 0.5rem; bottom: 0.5rem; background: rgba(255, 255, 255, 0.5); }
.TAB-btn div:nth-of-type(1):before { display: none; }
.TAB-btn em { font-size: 1.8rem; }

/* ---- */
@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>